﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ReportingSite.DAL;
using System.Data;
using ReportingSite.UserControls;
using System.Text;

namespace ReportingSite
{
    public partial class ReportPage : System.Web.UI.Page
    {
        DataTable dt = null;
        StringBuilder exportData = new StringBuilder();
        string type = "";

        int rowNumber = 0; 

        protected void Page_Load(object sender, EventArgs e)
        {
            Label lblPageHeading = (Label)Master.FindControl("lblPageHeading");
         
            /*
            Button btnSearch = (Button)Master.FindControl("btnSearch");
            TextBox txtSearch = (TextBox)Master.FindControl("txtSearch");

            btnSearch.Visible = true;
            txtSearch.Visible = true;
             */

            HeaderMenu headerMenu = (HeaderMenu)Master.FindControl("HeaderMenu");
            LinkButton lbLastMenu = (LinkButton)headerMenu.FindControl("lbLastMenu");

        
            LinkButton btnExportResult = (LinkButton) Master.FindControl("btnExportResult");
            btnExportResult.Text = "Export results to CSV";
            btnExportResult.Visible = true;

            type = Request.QueryString["type"].ToString();
            string range = Request.QueryString["range"].ToString();

            //if (range != "")
            //{
            //    lblTimeRange.Text = range;
            //}

            int hours = 0;
            

            switch (range)
            {
                case "24hrs": 
                    hours = 24;
                    break;
                case "72hrs":
                    hours = 72;
                    break;
                case "7days":
                    hours = 7 * 24;
                    break;
                case "14days":
                    hours = 14 * 24;
                    break;
                case "30days":
                    hours = 30 * 24;
                    break;
                default:
                    hours = 500000;
                    break;
            }



           

            switch (type)
            {
                case "person":
                    lblPageHeading.Text = "Person Object Report Page";
                    lbLastMenu.PostBackUrl = "~/ReportCriteria.aspx?type=person";
                    dt = SiteProvider.Person.GetPersonObjectReportByTimeRange(hours);
                    break;
                case "group":
                    lblPageHeading.Text = "Group Object Report Page";
                    lbLastMenu.PostBackUrl = "~/ReportCriteria.aspx?type=group";
                    dt = SiteProvider.Group.GetGroupObjectReportByTimeRange(hours);
                    break;
                default:
                    lblPageHeading.Text = "All Objects Report Page";
                    break;

            }

            if (dt != null) {
                gvObjectReport.DataSource = dt;
              
            } else
            {
                gvObjectReport.DataSource = new DataTable();
                gvObjectReport.BorderWidth = 0;
            }

            gvObjectReport.DataBind();
        }

        protected void LinkButton_Click(object sender, EventArgs e)
        {
            //handle all the link buttons in the footer 
            LinkButton lb = (LinkButton)sender;
            rowNumber = int.Parse(lb.Text) - 1;
            gvObjectReport.PageIndex = rowNumber;
            gvObjectReport.DataBind();



        }

        protected void gvObjectReport_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void gvObjectReport_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvObjectReport.PageIndex = e.NewPageIndex;
            gvObjectReport.DataBind();
        }

        private void Master_ExportData(object sender, EventArgs e)
        {
            //export to csv
            //show success or failure message
            Label lblMessage = (Label)Master.FindControl("lblMessage");


            if (dt == null)
            {
                lblMessage.Text = "There is no data to export.";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }
            else if (dt.Rows == null)
            {
                lblMessage.Text = "There is no data to export.";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }
            else if (dt.Rows.Count == 0)
            {
                lblMessage.Text = "There is no data to export.";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }
            else { 
             
           

            //convert dt data to csv 
            ConvertDTtoCSV();

         
            if (ExportToCSV() == true)
            {
                lblMessage.Text = "Report data exported successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                lblMessage.Text = "There was some error while exporting. Try again.";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }

            }

            lblMessage.Visible = true;


           

        }



        protected void Page_PreInit(object sender, EventArgs e)
        {
            Master.ExportData += new EventHandler(Master_ExportData);
        }

        private bool ExportToCSV()
        {
            
            try
            {

              

                //string sFileName = System.IO.Path.GetRandomFileName();
                //string sGenName = "Friendly.txt";

                //YOu could omit these lines here as you may
                //not want to save the textfile to the server
                //I have just left them here to demonstrate that you could create the text file 
                using (System.IO.StreamWriter SW = new System.IO.StreamWriter(
                       Server.MapPath("tempfile.csv")))
                {
                    SW.WriteLine(exportData.ToString());
                    SW.Close();
                }

                System.IO.FileStream fs = null;
                fs = System.IO.File.Open(Server.MapPath("tempfile.csv"), System.IO.FileMode.Open);
                byte[] btFile = new byte[fs.Length];
                fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
                fs.Close();
                Response.AddHeader("Content-disposition", "attachment; filename=ReportData.csv");
                Response.ContentType = "application/octet-stream";
                Response.BinaryWrite(btFile);
                Response.End();
            }
            catch (Exception e)
            {
                return false;
            }

            return true;
        }

        private void ConvertDTtoCSV()
        {
            string strRow = "";

            //add columns in the csv
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                
                strRow += dt.Columns[i].ColumnName; 

                if(i < dt.Columns.Count - 1)
                {
                    strRow += ","; 
                }
            }

            exportData.AppendLine(strRow); 

            //deal with all rows
            foreach (DataRow row in dt.Rows)
            {
                strRow = ""; 
                for (int i = 0; i < row.ItemArray.Length; i++)
                {
                    strRow += row[i].ToString();

                    if (i < row.ItemArray.Length - 1)
                    {
                        strRow += ","; 
                    }

                }

                exportData.AppendLine(strRow);

            }
        }

        protected void gvObjectReport_DataBound(object sender, EventArgs e)
        {
            GridViewRow pagerRow = gvObjectReport.BottomPagerRow;


            if (pagerRow != null)
            {
                LinkButton lbTemp;
                Label label1;
                pagerRow.HorizontalAlign = HorizontalAlign.Left;
                pagerRow.Cells[0].HorizontalAlign = HorizontalAlign.Left;
                pagerRow.Cells[0].CssClass = "divaligninpager";


                for (int i = 0; i < gvObjectReport.PageCount; i++)
                {
                    label1 = new Label();
                    label1.Text = "| ";
                    label1.ForeColor = System.Drawing.Color.FromName("#5F5F5F");
                    pagerRow.Cells[0].Controls.Add(label1);

                    lbTemp = new LinkButton();
                    lbTemp.ID = (i).ToString();
                    lbTemp.Text = (i + 1).ToString();
                    lbTemp.CssClass = "gridPageLinkActive";
                    lbTemp.Click += new EventHandler(LinkButton_Click);

                    pagerRow.Cells[0].Controls.Add(lbTemp);

                    label1 = new Label();
                    label1.Text = " ";
                    pagerRow.Cells[0].Controls.Add(label1);


                }

                ((LinkButton)pagerRow.Cells[0].FindControl(rowNumber.ToString())).Enabled = false;
                ((LinkButton)pagerRow.Cells[0].FindControl(rowNumber.ToString())).CssClass = "gridPageLinkCurrent";
            }
                
        }
    }
}